#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   router.py
@Time    :   2023/11/09 14:26:27
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from typing import List

from ninja.pagination import paginate
from django.shortcuts import get_object_or_404
from ninja import ModelSchema, Router
from .models import Music
from utils.response import Response
from utils.ninja import MyPagination


class MusicSchemaIn(ModelSchema):
    class Config:
        model = Music
        model_exclude = [
            "id",
            "last_play",
            "create_time",
            "update_time",
            "remark",
            "sort",
        ]


class MusicSchemaOut(ModelSchema):
    class Config:
        model = Music
        model_fields = "__all__"


router = Router()


# 查询所有
@router.get("/musics", auth=None, response=List[MusicSchemaOut])
@paginate(MyPagination)
def get_all_musics(request):
    query_set = Music.objects.all()
    return query_set


# 查询单个
@router.get("/musics/{mid}", auth=None, response=MusicSchemaOut)
def get_music_by_id(request, mid: int):
    query = Music.objects.filter(id=mid).first()
    return query


# 增
@router.post("/musics", auth=None, response=MusicSchemaOut)
def create_music(request, data: MusicSchemaIn):
    if not isinstance(data, dict):
        data = data.dict()
    query_set = Music.objects.create(**data)
    return query_set


# 改
@router.put("musics/{mid}", auth=None, response=MusicSchemaOut)
def update_music(request, mid: int, data: MusicSchemaIn):
    dict_data = data.dict()
    instance = get_object_or_404(Music, id=mid)
    for attr, value in dict_data.items():
        setattr(instance, attr, value)
    instance.save()
    return instance


# 删
@router.delete("/musics/{mid}", auth=None)
def delete_music(request, mid: int):
    instance = get_object_or_404(Music, id=mid)
    instance.delete()
    return {"success": True}
